﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TransCend.Result
{
    [Serializable]
    public class JsTreeResult : Result
    {
        private IList<JsTree> treelist = new List<JsTree>();
        private Dictionary<string, JsTree> rootMap = new Dictionary<string, JsTree>();

        public void Add(JsTree t)
        {
            Add(t, false);
        }

        public void Add(JsTree t, bool isRecursive) {
		    treelist.Add(t);
		    if(isRecursive) {
			    // 合并递归子结点
			    if(rootMap.ContainsKey(t.id)) {
				    IList<JsTree> list = rootMap[t.id].children;
				    if (list != null) {
					    foreach (JsTree tc in list) {
						    t.addChild(tc);
					    }
				    }
			    }
		    }
		    rootMap[t.id] = t;
	    }

        public JsTree Get(string id)
        {
            return rootMap[id];
        }

        public void AddChild(string id, JsTree t)
        {
            AddChild(id, t, false);
        }

        public void AddChild(string id, JsTree t, bool isRecursive) {
		    if(!string.IsNullOrEmpty(id)) {
			    if(isRecursive) {
				    // 不存在父，先建立虚结点
                    if (!rootMap.ContainsKey(id))
                    {
					    JsTree vt = new JsTree();
					    vt.id = id;
					    vt.text = "";
					    rootMap[id] = vt;
				    }
				    rootMap[id].addChild(t);
				
				    // 合并递归子结点
                    if (rootMap.ContainsKey(t.id))
                    {
					    IList<JsTree> list = rootMap[t.id].children;
					    if (list != null) {
						    foreach (JsTree tc in list) {
							    t.addChild(tc);
						    }
					    }
				    }
				    rootMap[t.id] = t;
			    } else if(rootMap.ContainsKey(id)) {
				    // 是否存在父结点
				    rootMap[id].addChild(t);
				    rootMap[t.id] = t;
			    } else {
				    Add(t, isRecursive);
			    }
		    } else {
                Add(t, isRecursive);
		    }
	    }

        public void AddList(IList<JsTree> list) {
		    foreach(JsTree t in list) {
                Add(t);
		    }
	    }

        public void AddChildList(string id, IList<JsTree> list) {
		    foreach(JsTree t in list) {
			    AddChild(id, t);
		    }
	    }

        public IList<JsTree> GetList()
        {
            return treelist;
        }

        public override object ToJsonObject()
        {
            return treelist;
        }

    }
}
